const { SuccessModel, ErrorModel } = require('../model/responseModel')
const {
  getList,
  getDetail,
  createNewBlog,
  updateBlog,
  deleteBlog,
} = require('../controllers/blog')

const { execSql } = require('../db/mysql')

// 处理博客相关路由
const handleBlogRoute = (req, res) => {
  // 定义处理路由的逻辑
  const method = req.method
  const id = req.query.id
  const postData = req.body
  if (method === 'GET' && req.path === '/api/blog/list') {
    const sql = `select * from blogs;`

    execSql(sql).then(() => {})

    const author = req.query.author || ''
    const keyword = req.query.keyword || ''
    const listData = getList(author, keyword)

    return new SuccessModel(listData)
  }

  if (method === 'GET' && req.path === '/api/blog/detail') {
    const detailData = getDetail(id)
    return new SuccessModel(detailData)
  }

  if (method === 'POST' && req.path === '/api/blog/new') {
    const newBlogData = createNewBlog(id, postData)
    return new SuccessModel(newBlogData)
  }

  if (method === 'POST' && req.path === '/api/blog/update') {
    const updatedBlogData = updateBlog(postData)
    if (updatedBlogData) {
      return new SuccessModel('更新博客成功...')
    } else {
      return new ErrorModel('更新博客失败...')
    }
  }

  if (method === 'POST' && req.path === '/api/blog/delete') {
    const deletedBlogData = deleteBlog(postData)
    if (deletedBlogData) {
      return new SuccessModel('删除博客成功...')
    } else {
      return new ErrorModel('删除博客失败...')
    }
  }
}

module.exports = handleBlogRoute
